package com.chenyi.system.service.impl;

import com.chenyi.common.annotation.AdminDataScope;
import com.chenyi.common.constant.UserConstants;
import com.chenyi.common.core.domain.entity.SysAdminRole;
import com.chenyi.common.exception.BadRequestException;
import com.chenyi.common.utils.StringUtils;
import com.chenyi.common.utils.spring.SpringUtils;
import com.chenyi.system.domain.SysAdminRoleDept;
import com.chenyi.system.domain.SysAdminRoleMenu;
import com.chenyi.system.mapper.SysAdminRoleAccessMapper;
import com.chenyi.system.mapper.SysAdminRoleDeptMapper;
import com.chenyi.system.mapper.SysAdminRoleMapper;
import com.chenyi.system.mapper.SysAdminRoleMenuMapper;
import com.chenyi.system.service.ISysAdminRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 角色 业务层处理
 * 
 * @author wangkh
 */
@Service
public class SysAdminRoleServiceImpl implements ISysAdminRoleService
{
    @Autowired
    private SysAdminRoleMapper roleMapper;

    @Autowired
    private SysAdminRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysAdminRoleAccessMapper userRoleMapper;

    @Autowired
    private SysAdminRoleDeptMapper roleDeptMapper;

    /**
     * 根据条件分页查询角色数据
     * 
     * @param adminRole 角色信息
     * @return 角色数据集合信息
     */
    @Override
    @AdminDataScope(deptAlias = "d")
    public List<SysAdminRole> selectAdminRoleList(SysAdminRole adminRole)
    {
        return roleMapper.selectAdminRoleList(adminRole);
    }

    /**
     * 根据用户ID查询权限
     * 
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectAdminRolePermissionByAdminId(Long userId)
    {
        List<SysAdminRole> perms = roleMapper.selectAdminRolePermissionByAdminId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysAdminRole perm : perms)
        {
            if (StringUtils.isNotNull(perm))
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询所有角色
     * 
     * @return 角色列表
     */
    @Override
    public List<SysAdminRole> selectAdminRoleAll()
    {
        return SpringUtils.getAopProxy(this).selectAdminRoleList(new SysAdminRole());
    }

    /**
     * 根据用户ID获取角色选择框列表
     * 
     * @param adminId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Integer> selectAdminRoleListByAdminId(Long adminId)
    {
        return roleMapper.selectAdminRoleListByAdminId(adminId);
    }

    /**
     * 通过角色ID查询角色
     * 
     * @param roleId 角色ID
     * @return 角色对象信息
     */
    @Override
    public SysAdminRole selectAdminRoleById(Long roleId)
    {
        return roleMapper.selectAdminRoleById(roleId);
    }

    /**
     * 校验角色名称是否唯一
     * 
     * @param adminRole 角色信息
     * @return 结果
     */
    @Override
    public String checkAdminRoleNameUnique(SysAdminRole adminRole)
    {
        Long roleId = StringUtils.isNull(adminRole.getRoleId()) ? -1L : adminRole.getRoleId();
        SysAdminRole info = roleMapper.checkAdminRoleNameUnique(adminRole.getRoleName());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色权限是否唯一
     * 
     * @param adminRole 角色信息
     * @return 结果
     */
    @Override
    public String checkAdminRoleKeyUnique(SysAdminRole adminRole)
    {
        Long roleId = StringUtils.isNull(adminRole.getRoleId()) ? -1L : adminRole.getRoleId();
        SysAdminRole info = roleMapper.checkAdminRoleKeyUnique(adminRole.getRoleKey());
        if (StringUtils.isNotNull(info) && info.getRoleId().longValue() != roleId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验角色是否允许操作
     * 
     * @param adminRole 角色信息
     */
    @Override
    public void checkAdminRoleAllowed(SysAdminRole adminRole)
    {
        if (StringUtils.isNotNull(adminRole.getRoleId()) && adminRole.isAdmin())
        {
            throw new BadRequestException("不允许操作超级管理员角色");
        }
    }

    /**
     * 通过角色ID查询角色使用数量
     * 
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int countAdminRoleAccessByRoleId(Long roleId)
    {
        return userRoleMapper.countUserRoleByRoleId(roleId);
    }

    /**
     * 新增保存角色信息
     * 
     * @param adminRole 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertAdminRole(SysAdminRole adminRole)
    {
        // 新增角色信息
        roleMapper.insertAdminRole(adminRole);
        return insertAdminRoleMenu(adminRole);
    }

    /**
     * 修改保存角色信息
     * 
     * @param adminRole 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateAdminRole(SysAdminRole adminRole)
    {
        // 修改角色信息
        roleMapper.updateAdminRole(adminRole);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(adminRole.getRoleId());
        return insertAdminRoleMenu(adminRole);
    }

    /**
     * 修改角色状态
     * 
     * @param adminRole 角色信息
     * @return 结果
     */
    @Override
    public int updateAdminRoleStatus(SysAdminRole adminRole)
    {
        return roleMapper.updateAdminRole(adminRole);
    }

    /**
     * 修改数据权限信息
     * 
     * @param adminRole 角色信息
     * @return 结果
     */
    @Override
    @Transactional
    public int authDataScope(SysAdminRole adminRole)
    {
        // 修改角色信息
        roleMapper.updateAdminRole(adminRole);
        // 删除角色与部门关联
        roleDeptMapper.deleteRoleDeptByRoleId(adminRole.getRoleId());
        // 新增角色和部门信息（数据权限）
        return insertAdminRoleDept(adminRole);
    }

    /**
     * 新增角色菜单信息
     * 
     * @param adminRole 角色对象
     */
    public int insertAdminRoleMenu(SysAdminRole adminRole)
    {
        int rows = 1;
        // 新增用户与角色管理
        List<SysAdminRoleMenu> list = new ArrayList<SysAdminRoleMenu>();
        for (Long menuId : adminRole.getMenuIds())
        {
            SysAdminRoleMenu rm = new SysAdminRoleMenu();
            rm.setRoleId(adminRole.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 新增角色部门信息(数据权限)
     *
     * @param adminRole 角色对象
     */
    public int insertAdminRoleDept(SysAdminRole adminRole)
    {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysAdminRoleDept> list = new ArrayList<SysAdminRoleDept>();
        for (Long deptId : adminRole.getDeptIds())
        {
            SysAdminRoleDept rd = new SysAdminRoleDept();
            rd.setRoleId(adminRole.getRoleId());
            rd.setDeptId(deptId);
            list.add(rd);
        }
        if (list.size() > 0)
        {
            rows = roleDeptMapper.batchRoleDept(list);
        }
        return rows;
    }

    /**
     * 通过角色ID删除角色
     * 
     * @param roleId 角色ID
     * @return 结果
     */
    @Override
    public int deleteAdminRoleById(Long roleId)
    {
        return roleMapper.deleteAdminRoleById(roleId);
    }

    /**
     * 批量删除角色信息
     * 
     * @param roleIds 需要删除的角色ID
     * @return 结果
     */
    @Override
    public int deleteAdminRoleByIds(Long[] roleIds)
    {
        for (Long roleId : roleIds)
        {
            checkAdminRoleAllowed(new SysAdminRole(roleId));
            SysAdminRole adminRole = selectAdminRoleById(roleId);
            if (countAdminRoleAccessByRoleId(roleId) > 0)
            {
                throw new BadRequestException(String.format("%1$s已分配,不能删除", adminRole.getRoleName()));
            }
        }
        return roleMapper.deleteAdminRoleByIds(roleIds);
    }
}
